package com.fangshi.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.fangshi.R
import com.fangshi.databinding.ListItemGarageBinding
import com.fangshi.viewmodels.Garage

class MyRecyclerViewAdapter(
    private val garages: List<Garage>,
    private val onItemSelected: (garageId: String) -> Unit
) : RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>() {

    class ViewHolder(binding: ListItemGarageBinding) : RecyclerView.ViewHolder(binding.root) {
        val tvName: TextView = binding.textView1
        val cardView = binding.linearLayout
        val selectImage = binding.selectedImage
        val tvCarCount = binding.carCount
    }

    private var curPos: Int = -1

    private fun setCurPos(pos: Int) {
        curPos = pos
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding: ListItemGarageBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.list_item_garage,
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.apply {
            tvName.text = garages[position].garageName
            tvName.tag = garages[position].garageId
            tvCarCount.text = garages[position].carCountDescribe

            if (position == curPos) {
                cardView.setBackgroundResource(R.color.purple_500)
                tvName.setTextColor(Color.WHITE)
                tvCarCount.setTextColor(Color.WHITE)
                selectImage.visibility = View.VISIBLE
            } else {
                cardView.setBackgroundResource(R.color.white)
                tvName.setTextColor(Color.BLACK)
                tvCarCount.setTextColor(Color.BLACK)
                selectImage.visibility = View.GONE
            }
            cardView.setOnClickListener {
                val lastPosition = curPos
                setCurPos(position)
                onItemSelected(garages[position].garageId!!)
                notifyItemChanged(position)
                notifyItemChanged(lastPosition)
            }
        }

    }

    override fun getItemCount(): Int {
        return garages.size
    }

}

